<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数学乐园 - 分数1/2的奥秘</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',     // 明亮友好的蓝色
                        secondary: '#EC4899',   // 活泼的粉色
                        accent: '#F59E0B',      // 温暖的橙色
                        neutral: '#64748B',     // 柔和的灰色
                        light: '#F8FAFC',       // 浅色背景
                    },
                    fontFamily: {
                        kids: ['"Comic Sans MS"', '"Marker Felt"', 'Arial Rounded MT Bold', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .fraction { display: inline-block; text-align: center; vertical-align: middle; margin: 0 0.2em; }
            .fraction .numerator { display: block; border-bottom: 1px solid #000; padding-bottom: 0.1em; }
            .fraction .denominator { display: block; padding-top: 0.1em; }
            .text-shadow {
                text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
            }
            .card-shadow {
                box-shadow: 0 8px 16px rgba(0,0,0,0.08);
            }
            .btn-pop {
                transition: transform 0.15s ease, box-shadow 0.15s ease;
            }
            .btn-pop:hover {
                transform: translateY(-2px);
                box-shadow: 0 6px 12px rgba(0,0,0,0.12);
            }
            .btn-pop:active {
                transform: translateY(0);
                box-shadow: 0 4px 8px rgba(0,0,0,0.08);
            }
            .slider-thumb {
                @apply appearance-none w-8 h-8 rounded-full bg-primary cursor-pointer shadow-md transition-all duration-200 hover:scale-110;
            }
            .slider-track {
                @apply appearance-none h-3 rounded-lg bg-gray-200;
            }
            .bounce-in {
                animation: bounceIn 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            }
            .float {
                animation: float 3s ease-in-out infinite;
            }
            @keyframes bounceIn {
                0% { transform: scale(0.9); opacity: 0; }
                70% { transform: scale(1.05); }
                100% { transform: scale(1); opacity: 1; }
            }
            @keyframes float {
                0% { transform: translateY(0px); }
                50% { transform: translateY(-8px); }
                100% { transform: translateY(0px); }
            }
        }
    </style>
</head>
<body class="bg-gradient-to-b from-blue-50 to-indigo-50 min-h-screen font-kids text-gray-800">
    <!-- 主内容区 -->
    <main class="container mx-auto p-4 md:p-6">
        <!-- 课程标题区 -->
        <div class="text-center mb-4 bounce-in">
            <h2 class="text-[clamp(1.25rem,5vw,1.75rem)] font-bold text-primary text-shadow mb-2">画一画，分一分，涂一涂，找出这些月饼的<span class="fraction"><span class="numerator">1</span><span class="denominator">2</span></span></h2>
        </div>
        
        <!-- 操作区域 - 调整间距使各区域更加清晰 -->
        <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
            <!-- 左侧工具区 -->
            <div class="lg:col-span-2 flex justify-center lg:justify-end order-2 lg:order-1">
                <div class="bg-white rounded-2xl p-3 card-shadow">
                    <div class="flex flex-col items-center gap-3">
                        <button id="drawButton" class="w-14 h-14 rounded-full bg-primary text-white flex items-center justify-center btn-pop">
                            <i class="fa fa-pencil text-2xl"></i>
                        </button>
                        <span class="text-sm text-center">画分割线</span>
                        
                        <button id="splitButton" class="w-14 h-14 rounded-full bg-gray-200 text-neutral flex items-center justify-center btn-pop opacity-50 cursor-not-allowed" disabled>
                            <i class="fa fa-scissors text-2xl"></i>
                        </button>
                        <span class="text-sm text-center">分割</span>
                        
                        <button id="colorButton" class="w-14 h-14 rounded-full bg-gray-200 text-neutral flex items-center justify-center btn-pop opacity-50 cursor-not-allowed" disabled>
                            <i class="fa fa-paint-brush text-2xl"></i>
                        </button>
                        <span class="text-sm text-center">涂出<span class="fraction"><span class="numerator">1</span><span class="denominator">2</span></span></span>
                        
                        <button id="checkButton" class="w-14 h-14 rounded-full bg-gray-200 text-neutral flex items-center justify-center btn-pop opacity-50 cursor-not-allowed" disabled>
                            <i class="fa fa-check-circle text-2xl"></i>
                        </button>
                        <span class="text-sm text-center">检查</span>
                        
                        <button id="resetButton" class="w-14 h-14 rounded-full bg-neutral text-white flex items-center justify-center btn-pop mt-2">
                            <i class="fa fa-refresh text-2xl"></i>
                        </button>
                        <span class="text-sm text-center">重置</span>
                    </div>
                </div>
            </div>
            
            <!-- 中间主内容区 -->
            <div class="lg:col-span-7 order-1 lg:order-2 flex flex-col">
                <!-- 月饼数量控制区 -->
                <div class="bg-white rounded-2xl p-4 card-shadow mb-3 bounce-in">
                    <div class="flex items-center gap-2 mb-2">
                        <div class="bg-accent/10 text-accent p-2 rounded-full">
                            <i class="fa fa-bell text-xl"></i>
                        </div>
                        <p class="text-lg font-medium text-neutral">⚡ 请先选择月饼的数量，再开始游戏哦！</p>
                    </div>
                    <div class="flex flex-wrap justify-center items-center gap-4">
                        <span class="text-lg font-semibold text-neutral w-full text-center md:w-auto md:text-right pr-0 md:pr-2">月饼数量:</span>
                        <div class="flex items-center gap-2 w-full md:w-auto">
                            <button id="decreaseCount" class="w-10 h-10 rounded-full border border-gray-300 bg-white text-gray-600 flex items-center justify-center hover:bg-gray-100 transition-colors">
                                <i class="fa fa-minus"></i>
                            </button>
                            <input type="range" id="mooncakeSlider" min="0" max="8" step="1" value="3" class="w-48 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer">
                            <button id="increaseCount" class="w-10 h-10 rounded-full border border-gray-300 bg-white text-gray-600 flex items-center justify-center hover:bg-gray-100 transition-colors">
                                <i class="fa fa-plus"></i>
                            </button>
                            <div id="countValue" class="w-12 h-12 rounded-full bg-primary text-white flex items-center justify-center text-xl font-bold shadow-lg">6</div>
                        </div>
                    </div>
                </div>
                
                <!-- 画布容器 -->
                <div class="bg-white rounded-2xl p-4 md:p-5 card-shadow bounce-in flex-grow" style="animation-delay: 0.2s">
                    <div class="flex justify-between items-center mb-2">
                        <h3 class="font-bold text-lg text-neutral">动手操作区</h3>
                    </div>
                    <canvas id="drawingCanvas" class="w-full rounded-xl border-2 border-gray-100 shadow-inner"></canvas>
                </div>
            </div>
            
            <!-- 右侧操作提示和反馈区 -->
            <div class="lg:col-span-3 order-3 flex flex-col">
                <!-- 提示卡片 -->
                <div class="bg-white rounded-2xl p-4 card-shadow mb-3 bounce-in" style="animation-delay: 0.1s">
                    <div class="flex items-start gap-2">
                        <div class="bg-primary/10 text-primary p-2 rounded-full mt-0.5">
                            <i class="fa fa-lightbulb-o text-xl"></i>
                        </div>
                        <p id="instruction-text" class="text-[clamp(1rem,3vw,1.25rem)] text-gray-700">
                            第一步：点击画笔按钮，在盒子上画一条线，试着把月饼平均分成两部分
                        </p>
                    </div>
                </div>
                
                <div id="feedback" class="hidden bg-white rounded-2xl p-5 card-shadow flex-grow bounce-in flex flex-col items-center text-center">
                    <div id="feedbackIcon" class="text-5xl mb-4 text-accent float"></div>
                    <h3 id="feedbackText" class="text-xl md:text-2xl font-bold mb-3 text-gray-800"></h3>
                    <p id="feedbackExplanation" class="text-neutral text-base md:text-lg flex-grow"></p>
                    <button id="nextButton" class="mt-4 bg-primary text-white px-6 py-2 rounded-full font-bold btn-pop">
                        继续探索 <i class="fa fa-arrow-right ml-1"></i>
                    </button>
                </div>
            </div>
        </div>
    </main>
    
    <!-- 页脚 -->
    <footer class="mt-4 bg-white py-3 px-6 text-center text-neutral text-xs">
        <p>分数的认识 © 小学三年级数学学习 | 杭州信达外国语学校</p>
    </footer>

    <script>
        // 获取Canvas元素和上下文
        const canvas = document.getElementById('drawingCanvas');
        const ctx = canvas.getContext('2d');
        
        // 获取按钮和其他DOM元素
        const drawButton = document.getElementById('drawButton');
        const splitButton = document.getElementById('splitButton');
        const colorButton = document.getElementById('colorButton');
        const checkButton = document.getElementById('checkButton');
        const resetButton = document.getElementById('resetButton');
        const nextButton = document.getElementById('nextButton');
        const instructionText = document.getElementById('instruction-text');
        const feedback = document.getElementById('feedback');
        const feedbackIcon = document.getElementById('feedbackIcon');
        const feedbackText = document.getElementById('feedbackText');
        const feedbackExplanation = document.getElementById('feedbackExplanation');
        const mooncakeSlider = document.getElementById('mooncakeCount');
        const countValue = document.getElementById('countValue');
        
        // 应用状态
        let mooncakeCount = 6; // 初始月饼数量
        let isDrawing = false;
        let isColoring = false;
        let isAnimating = false;
        let hasSplit = false;
        let isMouseDown = false;
        let splitLine = [];
        let cells = [];
        let cellWidth, cellHeight;
        let rows, cols; // 动态计算行列数
        let currentOffsetLeft = 0;
        let currentOffsetRight = 0;
        let targetOffsetLeft = 0;
        let targetOffsetRight = 0;
        
        // 定义可选的月饼数量数组
        const availableCounts = [1, 2, 3, 4, 6, 8, 9, 10, 12];
        
        // 初始化滑杆控制
        function initSlider() {
            const slider = document.getElementById('mooncakeSlider');
            const decreaseBtn = document.getElementById('decreaseCount');
            const increaseBtn = document.getElementById('increaseCount');
            const countDisplay = document.getElementById('countValue');
            
            // 设置初始显示值
            countDisplay.textContent = mooncakeCount;
            
            // 找到初始值在数组中的索引
            const initialIndex = availableCounts.indexOf(mooncakeCount);
            if (initialIndex !== -1) {
                slider.value = initialIndex;
            }
            
            // 滑杆变化事件
            slider.addEventListener('input', () => {
                if (!hasSplit && splitLine.length === 0) {
                    const index = parseInt(slider.value);
                    mooncakeCount = availableCounts[index];
                    countDisplay.textContent = mooncakeCount;
                    setupCanvas();
                }
            });
            
            // 减号按钮事件
            decreaseBtn.addEventListener('click', () => {
                if (!hasSplit && splitLine.length === 0) {
                    let currentIndex = availableCounts.indexOf(mooncakeCount);
                    if (currentIndex > 0) {
                        currentIndex--;
                        slider.value = currentIndex;
                        mooncakeCount = availableCounts[currentIndex];
                        countDisplay.textContent = mooncakeCount;
                        setupCanvas();
                    }
                }
            });
            
            // 加号按钮事件
            increaseBtn.addEventListener('click', () => {
                if (!hasSplit && splitLine.length === 0) {
                    let currentIndex = availableCounts.indexOf(mooncakeCount);
                    if (currentIndex < availableCounts.length - 1) {
                        currentIndex++;
                        slider.value = currentIndex;
                        mooncakeCount = availableCounts[currentIndex];
                        countDisplay.textContent = mooncakeCount;
                        setupCanvas();
                    }
                }
            });
        }
        
        // 设置Canvas尺寸和月饼布局
        function setupCanvas() {
            // 响应式尺寸
            const containerWidth = canvas.parentElement.clientWidth;
            const containerHeight = Math.min(containerWidth * 0.7, window.innerHeight * 0.45);
            
            canvas.width = containerWidth;
            canvas.height = containerHeight;
            
            // 根据月饼数量计算行列布局
            calculateGridLayout();
            
            // 计算单元格尺寸
            cellWidth = canvas.width / cols;
            cellHeight = canvas.height / rows;
            
            // 初始化单元格数据
            initializeCells();
            
            // 绘制初始状态
            drawCanvas();
        }
        
        // 根据月饼数量计算最佳行列布局
        function calculateGridLayout() {
            // 根据用户要求实现不同数量月饼的布局
            switch(mooncakeCount) {
                case 1:
                    // 1个月饼：2行2列
                    rows = 2;
                    cols = 2;
                    break;
                case 3:
                    // 3个月饼：2行6列
                    rows = 2;
                    cols = 6;
                    break;
                case 9:
                    // 9个月饼：6行6列
                    rows = 6;
                    cols = 6;
                    break;
                case 12:
                    // 12个月饼：8行6列
                    rows = 8;
                    cols = 6;
                    break;
                default:
                    // 其它数量：保持原布局（每行格子数=月饼数量，每列格子数=4）
                    cols = mooncakeCount;
                    rows = 4;
            }
        }
        
        // 初始化单元格数据
        function initializeCells() {
            cells = [];
            
            // 创建所有网格单元格
            for (let row = 0; row < rows; row++) {
                for (let col = 0; col < cols; col++) {
                    cells.push({
                        row,
                        col,
                        x: col * cellWidth,
                        y: row * cellHeight,
                        width: cellWidth,
                        height: cellHeight,
                        isColored: false,
                        colorProgress: 0, // 用于涂色动画
                        isLeft: null, // null: 未分割, true: 左侧部分, false: 右侧部分
                        mooncakeIndex: -1 // 属于哪个月饼，-1表示不包含月饼
                    });
                }
            }
            
            // 为每个月饼分配大格子（2x2的单元格组成一个大格子）
            let currentMooncake = 0;
            // 只在第1、2行和第3、4行创建大格子
            for (let bigRow = 0; bigRow < rows; bigRow += 2) {
                // 每两个列创建一个大格子
                for (let bigCol = 0; bigCol < cols; bigCol += 2) {
                    // 检查是否还有月饼需要分配
                    if (currentMooncake >= mooncakeCount) break;
                    
                    // 为2x2的单元格组分配同一个月饼索引
                    for (let rowOffset = 0; rowOffset < 2; rowOffset++) {
                        for (let colOffset = 0; colOffset < 2; colOffset++) {
                            const row = bigRow + rowOffset;
                            const col = bigCol + colOffset;
                            if (row < rows && col < cols) {
                                const index = row * cols + col;
                                cells[index].mooncakeIndex = currentMooncake;
                            }
                        }
                    }
                    currentMooncake++;
                }
            }
        }
        
        // 绘制更真实的盒子
        function drawRealisticBox() {
            const boxShadowOffset = 8;
            
            // 绘制阴影
            ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
            ctx.fillRect(boxShadowOffset, boxShadowOffset, canvas.width, canvas.height);
            
            // 创建渐变背景
            const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
            gradient.addColorStop(0, '#F8FAFC');
            gradient.addColorStop(1, '#EFF6FF');
            
            // 绘制盒子主体
            ctx.fillStyle = gradient;
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制盒子顶部和左侧高光
            ctx.strokeStyle = '#FFFFFF';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.moveTo(0, 0);
            ctx.lineTo(canvas.width, 0);
            ctx.moveTo(0, 0);
            ctx.lineTo(0, canvas.height);
            ctx.stroke();
            
            // 绘制盒子右侧和底部暗边
            ctx.strokeStyle = '#93C5FD';
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(canvas.width - 1, 0);
            ctx.lineTo(canvas.width - 1, canvas.height);
            ctx.moveTo(0, canvas.height - 1);
            ctx.lineTo(canvas.width, canvas.height - 1);
            ctx.stroke();
            
            // 绘制盒子外边框
            ctx.strokeStyle = '#3B82F6';
            ctx.lineWidth = 2;
            ctx.strokeRect(0, 0, canvas.width, canvas.height);
            
            // 添加一些细微的纹理效果
            ctx.fillStyle = 'rgba(59, 130, 246, 0.03)';
            for (let i = 0; i < 50; i++) {
                const x = Math.random() * canvas.width;
                const y = Math.random() * canvas.height;
                const size = Math.random() * 3 + 1;
                ctx.beginPath();
                ctx.arc(x, y, size, 0, Math.PI * 2);
                ctx.fill();
            }
        }
        
        // 绘制整个Canvas
        function drawCanvas() {
            // 清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制盒子 - 更真实的效果
            drawRealisticBox();
            
            // 绘制分割后的偏移
            if (hasSplit) {
                drawCellsWithOffset();
            } else {
                // 绘制网格线
                drawGrid();
                
                // 绘制月饼
                drawMooncakes();
            }
            
            // 绘制分割线
            if (splitLine.length > 0) {
                ctx.strokeStyle = '#EC4899';
                ctx.lineWidth = 4;
                ctx.beginPath();
                ctx.moveTo(splitLine[0].x, splitLine[0].y);
                
                for (let i = 1; i < splitLine.length; i++) {
                    ctx.lineTo(splitLine[i].x, splitLine[i].y);
                }
                
                ctx.stroke();
            }
            
            // 如果正在动画中，继续下一帧
            if (isAnimating) {
                requestAnimationFrame(drawCanvas);
            }
        }
        
        // 绘制网格线
        function drawGrid() {
            ctx.strokeStyle = '#E2E8F0';
            ctx.lineWidth = 2;
            
            // 垂直线
            for (let i = 1; i < cols; i++) {
                ctx.beginPath();
                ctx.moveTo(i * cellWidth, 0);
                ctx.lineTo(i * cellWidth, canvas.height);
                ctx.stroke();
            }
            
            // 水平线
            for (let i = 1; i < rows; i++) {
                ctx.beginPath();
                ctx.moveTo(0, i * cellHeight);
                ctx.lineTo(canvas.width, i * cellHeight);
                ctx.stroke();
            }
        }
        
        // 绘制月饼
        function drawMooncakes() {
            // 记录已经绘制的月饼
            const drawnMooncakes = new Set();
            
            cells.forEach(cell => {
                // 只在每个2x2单元格组的第一个单元格绘制月饼
                if (cell.mooncakeIndex !== -1 && !drawnMooncakes.has(cell.mooncakeIndex) && 
                    cell.row % 2 === 0 && cell.col % 2 === 0) {
                    
                    drawnMooncakes.add(cell.mooncakeIndex);
                    
                    // 计算2x2大格子的边界
                    const bigCellWidth = cell.width * 2;
                    const bigCellHeight = cell.height * 2;
                    const bigCellX = cell.x;
                    const bigCellY = cell.y;
                    
                    // 计算月饼位置和大小（稍大但不超过大格边界）
                    const mooncakeSize = Math.min(bigCellWidth, bigCellHeight) * 0.9;
                    const centerX = bigCellX + bigCellWidth / 2;
                    const centerY = bigCellY + bigCellHeight / 2;
                    const radius = mooncakeSize / 2;
                    
                    // 如果这个月饼所在的任何一个单元格被涂色，先填充背景
                    const hasColoredCell = cells.some(c => 
                        c.mooncakeIndex === cell.mooncakeIndex && c.colorProgress > 0
                    );
                    
                    if (hasColoredCell) {
                        ctx.fillStyle = 'rgba(45, 185, 171, 0.2)';
                        ctx.fillRect(bigCellX, bigCellY, bigCellWidth, bigCellHeight);
                    }
                    
                    // 创建月饼的径向渐变
                    const gradient = ctx.createRadialGradient(
                        centerX - radius * 0.3, centerY - radius * 0.3, radius * 0.1,
                        centerX, centerY, radius
                    );
                    gradient.addColorStop(0, '#FFE0B2'); // 高光
                    gradient.addColorStop(0.6, '#FFB74D'); // 主色
                    gradient.addColorStop(1, '#F57C00'); // 阴影
                    
                    // 绘制月饼主体
                    ctx.fillStyle = gradient;
                    ctx.beginPath();
                    ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
                    ctx.fill();
                    
                    // 绘制月饼边缘
                    ctx.strokeStyle = '#E65100';
                    ctx.lineWidth = 2;
                    ctx.beginPath();
                    ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
                    ctx.stroke();
                    
                    // 绘制月饼上的传统花纹 - 外圆环
                    ctx.strokeStyle = '#E65100';
                    ctx.lineWidth = 1.5;
                    ctx.beginPath();
                    ctx.arc(centerX, centerY, radius * 0.8, 0, Math.PI * 2);
                    ctx.stroke();
                    
                    // 绘制十字线
                    ctx.beginPath();
                    ctx.moveTo(centerX - radius * 0.7, centerY);
                    ctx.lineTo(centerX + radius * 0.7, centerY);
                    ctx.stroke();
                    
                    ctx.beginPath();
                    ctx.moveTo(centerX, centerY - radius * 0.7);
                    ctx.lineTo(centerX, centerY + radius * 0.7);
                    ctx.stroke();
                    
                    // 绘制中心装饰
                    ctx.fillStyle = '#E65100';
                    ctx.beginPath();
                    ctx.arc(centerX, centerY, radius * 0.15, 0, Math.PI * 2);
                    ctx.fill();
                }
            });
        }
        
        // 绘制有偏移的单元格（分割后）
        function drawCellsWithOffset() {
            // 记录已经绘制的月饼
            const drawnMooncakes = new Set();
            
            cells.forEach(cell => {
                let drawX = cell.x;
                let drawY = cell.y;

                // 根据分割后的位置应用偏移（带动画）
                if (cell.isHorizontalSplit) {
                    // 横向分割线：上方单元格向上移，下方单元格向下移
                    if (cell.isLeft) {
                        drawY -= currentOffsetLeft;
                    } else {
                        drawY += currentOffsetRight;
                    }
                } else {
                    // 纵向分割线：左侧单元格向左移，右侧单元格向右移
                    if (cell.isLeft) {
                        drawX -= currentOffsetLeft;
                    } else {
                        drawX += currentOffsetRight;
                    }
                }

                // 如果单元格被涂色，先填充背景（带动画）
                if (cell.colorProgress > 0) {
                    ctx.fillStyle = `rgba(45, 185, 171, ${0.2 * cell.colorProgress})`;
                    ctx.fillRect(drawX, drawY, cell.width, cell.height);
                }

                // 绘制单元格边框
                ctx.strokeStyle = '#E2E8F0';
                ctx.lineWidth = 2;
                ctx.strokeRect(drawX, drawY, cell.width, cell.height);
            });
            
            // 在第二次遍历中绘制月饼，确保每个月饼只绘制一次
            cells.forEach(cell => {
                // 只在每个2x2单元格组的左上角单元格绘制月饼
                if (cell.mooncakeIndex !== -1 && !drawnMooncakes.has(cell.mooncakeIndex) && 
                    cell.row % 2 === 0 && cell.col % 2 === 0) {
                    
                    drawnMooncakes.add(cell.mooncakeIndex);
                    
                    // 计算2x2大格子的边界和偏移后的位置
                    const bigCellWidth = cell.width * 2;
                    const bigCellHeight = cell.height * 2;
                    
                    // 检查这个月饼是否被分割
                    // 找到这个月饼的所有单元格
                    const moonCells = cells.filter(c => c.mooncakeIndex === cell.mooncakeIndex);
                    const hasLeft = moonCells.some(c => c.isLeft);
                    const hasRight = moonCells.some(c => !c.isLeft);
                    
                    // 如果月饼被分割线穿过（同时有左侧/上方和右侧/下方的单元格）
                    if (hasLeft && hasRight) {
                        // 找到左侧/上方和右侧/下方的单元格组
                        const leftCells = moonCells.filter(c => c.isLeft);
                        const rightCells = moonCells.filter(c => !c.isLeft);
                        
                        // 根据分割线方向绘制不同的半块月饼
                        if (cell.isHorizontalSplit) {
                            // 横向分割线：绘制上下两半
                            
                            // 绘制上半个月饼
                            if (leftCells.length > 0) {
                                // 找到最左上角的上方单元格
                                const topCell = leftCells.sort((a, b) => {
                                    if (a.row !== b.row) return a.row - b.row;
                                    return a.col - b.col;
                                })[0];
                                const topX = cell.x; // 使用原始单元格的x坐标确保左右对齐
                                const topY = topCell.y - currentOffsetLeft;
                                drawHalfMooncake(topX, topY, bigCellWidth, bigCellHeight, true, true);
                            }
                            
                            // 绘制下半个月饼
                            if (rightCells.length > 0) {
                                // 找到最左上角的下方单元格
                                const bottomCell = rightCells.sort((a, b) => {
                                    if (a.row !== b.row) return a.row - b.row;
                                    return a.col - b.col;
                                })[0];
                                const bottomX = cell.x; // 使用原始单元格的x坐标确保左右对齐
                                // 计算下半个月饼的正确位置
                                // 将下半个月饼向上移动一个单元格的高度，放置在正确的行
                                const bottomY = bottomCell.y - cell.height + currentOffsetRight;
                                drawHalfMooncake(bottomX, bottomY, bigCellWidth, bigCellHeight, false, true);
                            }
                        } else {
                            // 纵向分割线：绘制左右两半
                            
                            // 绘制左侧半个月饼
                            if (leftCells.length > 0) {
                                // 找到最左上角的左侧单元格
                                const leftCell = leftCells.sort((a, b) => {
                                    if (a.row !== b.row) return a.row - b.row;
                                    return a.col - b.col;
                                })[0];
                                const leftX = leftCell.x - currentOffsetLeft;
                                const leftY = cell.y; // 使用原始单元格的y坐标确保上下对齐
                                drawHalfMooncake(leftX, leftY, bigCellWidth, bigCellHeight, true, false);
                            }
                            
                            // 绘制右侧半个月饼
                            if (rightCells.length > 0) {
                                // 找到最左上角的右侧单元格
                                const rightCell = rightCells.sort((a, b) => {
                                    if (a.row !== b.row) return a.row - b.row;
                                    return a.col - b.col;
                                })[0];
                                // 计算右侧半个月饼的正确位置
                                // 将右侧半个月饼向左移动一个单元格的宽度，放置在正确的列
                                const rightX = rightCell.x - cell.width + currentOffsetRight;
                                const rightY = cell.y; // 使用原始单元格的y坐标确保上下对齐
                                drawHalfMooncake(rightX, rightY, bigCellWidth, bigCellHeight, false, false);
                            }
                        }
                    } else {
                        // 未被分割的月饼，计算偏移后的位置
                        let bigCellX = cell.x;
                        let bigCellY = cell.y;
                        
                        if (cell.isHorizontalSplit) {
                            // 横向分割线：根据上下位置应用偏移
                            if (cell.isLeft) {
                                bigCellY -= currentOffsetLeft;
                            } else {
                                bigCellY += currentOffsetRight;
                            }
                        } else {
                            // 纵向分割线：根据左右位置应用偏移
                            if (cell.isLeft) {
                                bigCellX -= currentOffsetLeft;
                            } else {
                                bigCellX += currentOffsetRight;
                            }
                        }
                        
                        // 计算月饼位置和大小
                        const mooncakeSize = Math.min(bigCellWidth, bigCellHeight) * 0.9;
                        const centerX = bigCellX + bigCellWidth / 2;
                        const centerY = bigCellY + bigCellHeight / 2;
                        const radius = mooncakeSize / 2;
                        
                        // 创建月饼的径向渐变
                        const gradient = ctx.createRadialGradient(
                            centerX - radius * 0.3, centerY - radius * 0.3, radius * 0.1,
                            centerX, centerY, radius
                        );
                        gradient.addColorStop(0, '#FFE0B2'); // 高光
                        gradient.addColorStop(0.6, '#FFB74D'); // 主色
                        gradient.addColorStop(1, '#F57C00'); // 阴影
                        
                        // 绘制月饼主体
                        ctx.fillStyle = gradient;
                        ctx.beginPath();
                        ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 绘制月饼边缘
                        ctx.strokeStyle = '#E65100';
                        ctx.lineWidth = 2;
                        ctx.beginPath();
                        ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
                        ctx.stroke();
                        
                        // 绘制月饼上的传统花纹 - 外圆环
                        ctx.strokeStyle = '#E65100';
                        ctx.lineWidth = 1.5;
                        ctx.beginPath();
                        ctx.arc(centerX, centerY, radius * 0.8, 0, Math.PI * 2);
                        ctx.stroke();
                        
                        // 绘制十字线
                        ctx.beginPath();
                        ctx.moveTo(centerX - radius * 0.7, centerY);
                        ctx.lineTo(centerX + radius * 0.7, centerY);
                        ctx.stroke();
                        
                        ctx.beginPath();
                        ctx.moveTo(centerX, centerY - radius * 0.7);
                        ctx.lineTo(centerX, centerY + radius * 0.7);
                        ctx.stroke();
                        
                        // 绘制中心装饰
                        ctx.fillStyle = '#E65100';
                        ctx.beginPath();
                        ctx.arc(centerX, centerY, radius * 0.15, 0, Math.PI * 2);
                        ctx.fill();
                    }
                }
            });
            
            // 绘制分割线
            if (splitLine.length > 0) {
                ctx.strokeStyle = '#EC4899';
                ctx.lineWidth = 4;
                ctx.beginPath();
                ctx.moveTo(splitLine[0].x, splitLine[0].y);

                for (let i = 1; i < splitLine.length; i++) {
                    ctx.lineTo(splitLine[i].x, splitLine[i].y);
                }

                ctx.stroke();
            }
            
            // 确保分割状态在动画完成后仍然保持
            if (hasSplit) {
                // 保持分割后的偏移量，不重置
                currentOffsetLeft = targetOffsetLeft;
                currentOffsetRight = targetOffsetRight;
            }
        }
        
        // 绘制半个月饼的辅助函数
        function drawHalfMooncake(x, y, width, height, isLeftHalf, isHorizontalSplit) {
            const mooncakeSize = Math.min(width, height) * 0.9;
            const centerX = x + width / 2;
            const centerY = y + height / 2;
            const radius = mooncakeSize / 2;
            
            // 创建月饼的径向渐变
            const gradient = ctx.createRadialGradient(
                centerX - radius * 0.3, centerY - radius * 0.3, radius * 0.1,
                centerX, centerY, radius
            );
            gradient.addColorStop(0, '#FFE0B2'); // 高光
            gradient.addColorStop(0.6, '#FFB74D'); // 主色
            gradient.addColorStop(1, '#F57C00'); // 阴影
            
            // 绘制半个月饼
            ctx.fillStyle = gradient;
            ctx.beginPath();
            if (isHorizontalSplit) {
                if (isLeftHalf) {
                    // 绘制上半圆
                    ctx.arc(centerX, centerY, radius, Math.PI, 0);
                } else {
                    // 绘制下半圆
                    ctx.arc(centerX, centerY, radius, 0, Math.PI);
                }
            } else {
                if (isLeftHalf) {
                    // 绘制左半圆
                    ctx.arc(centerX, centerY, radius, Math.PI * 0.5, Math.PI * 1.5);
                } else {
                    // 绘制右半圆
                    ctx.arc(centerX, centerY, radius, Math.PI * 1.5, Math.PI * 0.5);
                }
            }
            ctx.lineTo(centerX, centerY);
            ctx.closePath();
            ctx.fill();
            
            // 绘制月饼边缘
            ctx.strokeStyle = '#E65100';
            ctx.lineWidth = 2;
            ctx.beginPath();
            if (isHorizontalSplit) {
                if (isLeftHalf) {
                    ctx.arc(centerX, centerY, radius, Math.PI, 0);
                } else {
                    ctx.arc(centerX, centerY, radius, 0, Math.PI);
                }
            } else {
                if (isLeftHalf) {
                    ctx.arc(centerX, centerY, radius, Math.PI * 0.5, Math.PI * 1.5);
                } else {
                    ctx.arc(centerX, centerY, radius, Math.PI * 1.5, Math.PI * 0.5);
                }
            }
            ctx.lineTo(centerX, centerY);
            ctx.closePath();
            ctx.stroke();
            
            // 绘制月饼上的传统花纹 - 半圆环
            ctx.strokeStyle = '#E65100';
            ctx.lineWidth = 1.5;
            ctx.beginPath();
            if (isHorizontalSplit) {
                if (isLeftHalf) {
                    ctx.arc(centerX, centerY, radius * 0.8, Math.PI, 0);
                } else {
                    ctx.arc(centerX, centerY, radius * 0.8, 0, Math.PI);
                }
            } else {
                if (isLeftHalf) {
                    ctx.arc(centerX, centerY, radius * 0.8, Math.PI * 0.5, Math.PI * 1.5);
                } else {
                    ctx.arc(centerX, centerY, radius * 0.8, Math.PI * 1.5, Math.PI * 0.5);
                }
            }
            ctx.stroke();
            
            // 绘制中心装饰
            ctx.fillStyle = '#E65100';
            ctx.beginPath();
            ctx.arc(centerX, centerY, radius * 0.15, 0, Math.PI * 2);
            ctx.fill();
        }
        
        // 动画更新函数
        function updateAnimation() {
            // 缓动函数 - 让动画更自然
            const easeOut = (t) => 1 - Math.pow(1 - t, 3);
            const progress = targetOffsetLeft > 0 ? 1 - Math.abs(currentOffsetLeft / targetOffsetLeft) : 0;
            const easeProgress = easeOut(progress);
            
            // 更新偏移量
            if (currentOffsetLeft < targetOffsetLeft) {
                currentOffsetLeft += 2 + easeProgress * 3;
                if (currentOffsetLeft > targetOffsetLeft) currentOffsetLeft = targetOffsetLeft;
            }
            
            if (currentOffsetRight < targetOffsetRight) {
                currentOffsetRight += 2 + easeProgress * 3;
                if (currentOffsetRight > targetOffsetRight) currentOffsetRight = targetOffsetRight;
            }
            
            // 更新涂色动画
            cells.forEach(cell => {
                if (cell.isColored && cell.colorProgress < 1) {
                    cell.colorProgress += 0.05;
                    if (cell.colorProgress > 1) cell.colorProgress = 1;
                } else if (!cell.isColored && cell.colorProgress > 0) {
                    cell.colorProgress -= 0.05;
                    if (cell.colorProgress < 0) cell.colorProgress = 0;
                }
            });
            
            // 检查动画是否完成，但保持分割状态
            if (currentOffsetLeft >= targetOffsetLeft && currentOffsetRight >= targetOffsetRight &&
                cells.every(cell => (cell.isColored && cell.colorProgress >= 1) || 
                                   (!cell.isColored && cell.colorProgress <= 0))) {
                isAnimating = false;
            }
            
            drawCanvas();
            
            // 如果仍在动画中，继续请求下一帧
            if (isAnimating) {
                requestAnimationFrame(updateAnimation);
            }
        }
        
        // 确定单元格是在分割线的左侧/右侧或上侧/下侧
        function determineCellPositions() {
            if (splitLine.length < 2) return;

            // 使用简化的算法：计算每个单元格中心相对于分割线的位置
            const lineStart = splitLine[0];
            const lineEnd = splitLine[splitLine.length - 1];

            // 判断分割线是横向还是纵向
            const isHorizontal = Math.abs(lineEnd.x - lineStart.x) > Math.abs(lineEnd.y - lineStart.y);
            
            // 首先确定每个单元格在分割线的哪一侧
            cells.forEach(cell => {
                const cellCenter = {
                    x: cell.x + cell.width / 2,
                    y: cell.y + cell.height / 2
                };

                // 计算点到直线的交叉乘积以确定位置
                const crossProduct = 
                    (lineEnd.x - lineStart.x) * (cellCenter.y - lineStart.y) - 
                    (lineEnd.y - lineStart.y) * (cellCenter.x - lineStart.x);

                // 记录分割线方向
                cell.isHorizontalSplit = isHorizontal;
                
                // 正值表示在直线左侧或上方，负值表示在右侧或下方
                if (isHorizontal) {
                    // 横向分割线：true表示上方，false表示下方
                    cell.isLeft = crossProduct < 0;
                } else {
                    // 纵向分割线：true表示左侧，false表示右侧
                    cell.isLeft = crossProduct > 0;
                }
            });

            // 检查并处理被分割线穿过的月饼
            // 创建一个映射，记录每个月饼对应的单元格
            const mooncakeCellsMap = new Map();
            cells.forEach(cell => {
                if (cell.mooncakeIndex !== -1) {
                    if (!mooncakeCellsMap.has(cell.mooncakeIndex)) {
                        mooncakeCellsMap.set(cell.mooncakeIndex, []);
                    }
                    mooncakeCellsMap.get(cell.mooncakeIndex).push(cell);
                }
            });

            // 遍历每个月饼，检查是否被分割线穿过
            mooncakeCellsMap.forEach((moonCells, mooncakeIndex) => {
                const hasLeft = moonCells.some(cell => cell.isLeft);
                const hasRight = moonCells.some(cell => !cell.isLeft);
                
                // 如果月饼被分割线穿过（同时有左侧/上方和右侧/下方的单元格）
                if (hasLeft && hasRight) {
                    // 标记为被分割的月饼
                    moonCells.forEach(cell => {
                        cell.isHalfMooncake = true;
                    });
                }
            });

            // 设置分割偏移量目标值 - 确保分割后保持分开状态
            targetOffsetLeft = 30;
            targetOffsetRight = 30;

            // 开始分割动画
            hasSplit = true;
            isAnimating = true;
            updateAnimation();

            // 为分割线添加轻微的脉动效果
            animateSplitLine();
        }
        
        // 分割线脉动动画
        function animateSplitLine() {
            if (!hasSplit || splitLine.length < 2) return;
            
            let opacity = 1;
            let increasing = false;
            
            function pulse() {
                if (!hasSplit) return;
                
                if (increasing) {
                    opacity += 0.02;
                    if (opacity >= 1) increasing = false;
                } else {
                    opacity -= 0.02;
                    if (opacity <= 0.7) increasing = true;
                }
                
                // 重绘分割线以更新透明度
                ctx.strokeStyle = `rgba(236, 72, 153, ${opacity})`;
                ctx.lineWidth = 4;
                ctx.beginPath();
                ctx.moveTo(splitLine[0].x, splitLine[0].y);
                
                for (let i = 1; i < splitLine.length; i++) {
                    ctx.lineTo(splitLine[i].x, splitLine[i].y);
                }
                
                ctx.stroke();
                
                requestAnimationFrame(pulse);
            }
            
            pulse();
        }
        
        // 检查答案是否正确
        function checkAnswer() {
            const halfCount = mooncakeCount / 2;
            
            // 创建一个映射，记录每个月饼对应的单元格
            const mooncakeCellsMap = new Map();
            cells.forEach(cell => {
                if (cell.mooncakeIndex !== -1) {
                    if (!mooncakeCellsMap.has(cell.mooncakeIndex)) {
                        mooncakeCellsMap.set(cell.mooncakeIndex, []);
                    }
                    mooncakeCellsMap.get(cell.mooncakeIndex).push(cell);
                }
            });
            
            // 计算涂色的月饼数量（包括完整月饼和半个月饼）
            let coloredMooncakeCount = 0;
            
            // 遍历每个月饼
            mooncakeCellsMap.forEach((moonCells, mooncakeIndex) => {
                const hasLeft = moonCells.some(cell => cell.isLeft);
                const hasRight = moonCells.some(cell => !cell.isLeft);
                
                // 检查这个月饼是否被分割线穿过
                if (hasLeft && hasRight) {
                    // 被分割的月饼
                    const leftColored = moonCells.some(cell => cell.isLeft && cell.isColored);
                    const rightColored = moonCells.some(cell => !cell.isLeft && cell.isColored);
                    
                    if (leftColored && rightColored) {
                        // 如果两侧都被涂色，算一个完整月饼
                        coloredMooncakeCount += 1;
                    } else if (leftColored || rightColored) {
                        // 如果只有一侧被涂色，算半个月饼
                        coloredMooncakeCount += 0.5;
                    }
                } else {
                    // 未被分割的月饼
                    const isColored = moonCells.some(cell => cell.isColored);
                    if (isColored) {
                        coloredMooncakeCount += 1;
                    }
                }
            });
            
            // 检查是否涂色了总数的一半（考虑浮点数精度问题）
            if (Math.abs(coloredMooncakeCount - halfCount) > 0.01) {
                showFeedback(false, 
                    "再试试吧！", 
                    `想一想：你把${mooncakeCount}个月饼平均分了吗？平均分成了几份？现在要涂出几份？`);
                return;
            }

            // 检查涂色的是否是一整个部分
            const firstColoredIsLeft = cells.find(cell => cell.isColored)?.isLeft;
            const allSameSide = cells.every(cell => 
                !cell.isColored || cell.isLeft === firstColoredIsLeft
            );

            if (allSameSide) {
                showFeedback(true, 
                    "你太厉害了！", 
                    `完全正确！你找到了这盒月饼的<span class="fraction"><span class="numerator">1</span><span class="denominator">2</span></span>！记住哦，<span class="fraction"><span class="numerator">1</span><span class="denominator">2</span></span>就是把一个整体平均分成2份，表示其中1份。`);
            } else {
                showFeedback(false, 
                    "快成功啦！", 
                    `数量是对的，但要选择一整个部分哦！试着只涂左边或者只涂右边的${halfCount}个月饼。`);
            }
        }
        
        // 显示反馈信息（带动画）
        function showFeedback(isCorrect, text, explanation) {
            feedback.classList.remove('hidden');
            feedback.classList.add('bounce-in');
            
            feedbackText.textContent = text;
            feedbackExplanation.innerHTML = explanation;
            
            if (isCorrect) {
                feedbackIcon.className = 'fa fa-trophy text-accent text-5xl mb-4 float';
                nextButton.textContent = "再来一次";
                nextButton.innerHTML = "再来一次 <i class='fa fa-refresh ml-1'></i>";
            } else {
                feedbackIcon.className = 'fa fa-lightbulb-o text-primary text-5xl mb-4';
                nextButton.textContent = "继续尝试";
                nextButton.innerHTML = "继续尝试 <i class='fa fa-arrow-left ml-1'></i>";
            }
        }
        
        // 重置所有状态
        function resetAll() {
            isDrawing = false;
            isColoring = false;
            isAnimating = false;
            hasSplit = false;
            splitLine = [];
            currentOffsetLeft = 0;
            currentOffsetRight = 0;
            targetOffsetLeft = 0;
            targetOffsetRight = 0;
            
            // 重置画布光标
            canvas.style.cursor = 'default';
            
            // 重置按钮状态和样式
            drawButton.disabled = false;
            drawButton.classList.remove('opacity-50', 'cursor-not-allowed', 'bg-gray-200', 'text-neutral');
            drawButton.classList.add('bg-primary', 'text-white');
            
            splitButton.disabled = true;
            splitButton.classList.add('opacity-50', 'cursor-not-allowed', 'bg-gray-200', 'text-neutral');
            splitButton.classList.remove('bg-secondary', 'text-white');
            
            colorButton.disabled = true;
            colorButton.classList.add('opacity-50', 'cursor-not-allowed', 'bg-gray-200', 'text-neutral');
            colorButton.classList.remove('bg-secondary', 'text-white');
            
            checkButton.disabled = true;
            checkButton.classList.add('opacity-50', 'cursor-not-allowed', 'bg-gray-200', 'text-neutral');
            checkButton.classList.remove('bg-accent', 'text-white');
            
            // 重置提示和反馈
            instructionText.innerHTML =
                "第一步：点击画笔按钮，在盒子上画一条线，试着把这盒月饼平均分成两部分";
            feedback.classList.add('hidden');
            
            // 重新初始化单元格
            initializeCells();
            
            // 重绘画布
            drawCanvas();
        }
        
        // 事件监听器：绘制模式
        drawButton.addEventListener('click', () => {
            isDrawing = true;
            isColoring = false;
            
            // 更改光标样式为稍大的铅笔，调整热点位置使其与铅笔末端对齐
            canvas.style.cursor = 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'32\' height=\'32\' viewBox=\'0 0 32 32\' fill=\'%23EC4899\'%3E%3Cpath d=\'M21.65 4.75l-11.32 11.32-4.72-4.72 1.88-1.88 2.84 2.84 9.44-9.44 1.88 1.88z\'/%3E%3C/svg%3E") 5 28, auto';
            
            instructionText.innerHTML =
        "太棒了！现在请你在盒子上画一条线，试着把这盒月饼分一分，然后点击”分割“按钮";
            
            // 更新按钮状态和样式
            drawButton.disabled = true;
            drawButton.classList.add('opacity-50', 'cursor-not-allowed', 'bg-gray-200', 'text-neutral');
            drawButton.classList.remove('bg-primary', 'text-white');
            
            splitButton.disabled = false;
            splitButton.classList.remove('opacity-50', 'cursor-not-allowed', 'bg-gray-200', 'text-neutral');
            splitButton.classList.add('bg-secondary', 'text-white');
        });
        
        // 事件监听器：分割
        splitButton.addEventListener('click', () => {
            isDrawing = false;
            canvas.style.cursor = 'default';
            
            determineCellPositions();
            
            instructionText.innerHTML =
                `太好了！现在请点击"涂<span class="fraction"><span class="numerator">1</span><span class="denominator">2</span></span>"按钮，然后涂出你认为是这盒月饼的<span class="fraction"><span class="numerator">1</span><span class="denominator">2</span></span>的部分`;
            
            // 更新按钮状态和样式
            splitButton.disabled = true;
            splitButton.classList.add('opacity-50', 'cursor-not-allowed', 'bg-gray-200', 'text-neutral');
            splitButton.classList.remove('bg-secondary', 'text-white');
            
            colorButton.disabled = false;
            colorButton.classList.remove('opacity-50', 'cursor-not-allowed', 'bg-gray-200', 'text-neutral');
            colorButton.classList.add('bg-secondary', 'text-white');
        });
        
        // 事件监听器：涂色模式
        colorButton.addEventListener('click', () => {
            isColoring = true;
            isDrawing = false;
            canvas.style.cursor = 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'32\' height=\'32\' viewBox=\'0 0 32 32\'%3E%3Ccircle cx=\'16\' cy=\'16\' r=\'12\' fill=\'%23EC4899\' fill-opacity=\'0.7\'/%3E%3C/svg%3E") 16 16, auto';
            
            instructionText.innerHTML =
                `真棒！请涂出你认为是这盒月饼的<span class="fraction"><span class="numerator">1</span><span class="denominator">2</span></span>的部分，涂好后点击"检查"按钮`;
            
            // 更新按钮状态和样式
            colorButton.disabled = true;
            colorButton.classList.add('opacity-50', 'cursor-not-allowed', 'bg-gray-200', 'text-neutral');
            colorButton.classList.remove('bg-secondary', 'text-white');
            
            checkButton.disabled = false;
            checkButton.classList.remove('opacity-50', 'cursor-not-allowed', 'bg-gray-200', 'text-neutral');
            checkButton.classList.add('bg-accent', 'text-white');
        });
        
        // 事件监听器：检查答案
        checkButton.addEventListener('click', () => {
            isColoring = false;
            canvas.style.cursor = 'default';
            checkAnswer();
        });
        
        // 事件监听器：重置
        resetButton.addEventListener('click', resetAll);
        
        // 事件监听器：下一步/再试一次
        nextButton.addEventListener('click', () => {
            feedback.classList.add('hidden');
            // 如果已经答对了，就完全重置
            if (feedbackIcon.classList.contains('fa-trophy')) {
                resetAll();
            }
        });
        
        // 鼠标按下事件
        canvas.addEventListener('mousedown', (e) => {
            isMouseDown = true;
            
            if (!isDrawing && !isColoring) return;
            
            const rect = canvas.getBoundingClientRect();
            const x = e.clientX;
            const y = e.clientY;
            
            const canvasX = x - rect.left;
            const canvasY = y - rect.top;
            
            if (isDrawing) {
                // 开始绘制分割线（可以从盒子外开始）
                splitLine = [{ x: canvasX, y: canvasY }];
                drawCanvas();
            } else if (isColoring) {
                // 涂色模式：找到点击的单元格
                const col = Math.floor(canvasX / cellWidth);
                const row = Math.floor(canvasY / cellHeight);
                const index = row * cols + col;
                
                if (index >= 0 && index < cells.length) {
                    // 切换涂色状态并启动动画
                    cells[index].isColored = !cells[index].isColored;
                    
                    if (!isAnimating) {
                        isAnimating = true;
                        updateAnimation();
                    }
                }
            }
        });
        
        // 鼠标移动事件
        canvas.addEventListener('mousemove', (e) => {
            if (!isMouseDown) return;
            
            const rect = canvas.getBoundingClientRect();
            const x = e.clientX;
            const y = e.clientY;
            
            if (isDrawing) {
                // 计算光标在画布上的精确位置，确保与铅笔末端对齐
                const scaleX = canvas.width / rect.width;
                const scaleY = canvas.height / rect.height;
                const canvasX = (x - rect.left) * scaleX;
                const canvasY = (y - rect.top) * scaleY;
                
                // 添加点到分割线（可以超出盒子范围）
                splitLine.push({ x: canvasX, y: canvasY });
                drawCanvas();
            } else if (isColoring) {
                // 涂色模式：找到鼠标移动经过的单元格
                const canvasX = x - rect.left;
                const canvasY = y - rect.top;
                
                const col = Math.floor(canvasX / cellWidth);
                const row = Math.floor(canvasY / cellHeight);
                const index = row * cols + col;
                
                if (index >= 0 && index < cells.length && !cells[index].isColored) {
                    // 设置单元格为涂色状态并启动动画
                    cells[index].isColored = true;
                    
                    if (!isAnimating) {
                        isAnimating = true;
                        updateAnimation();
                    }
                }
            }
        });
        
        // 鼠标释放事件
        canvas.addEventListener('mouseup', () => {
            isMouseDown = false;
        });
        
        canvas.addEventListener('mouseout', () => {
            isMouseDown = false;
        });
        
        // 绑定触摸事件（支持移动设备）
        canvas.addEventListener('touchstart', (e) => {
            e.preventDefault(); // 防止触摸事件的默认行为
            isMouseDown = true;
            
            if (!isDrawing && !isColoring) return;
            
            const rect = canvas.getBoundingClientRect();
            const x = e.touches[0].clientX;
            const y = e.touches[0].clientY;
            
            const canvasX = x - rect.left;
            const canvasY = y - rect.top;
            
            if (isDrawing) {
                // 开始绘制分割线
                splitLine = [{ x: canvasX, y: canvasY }];
                drawCanvas();
            } else if (isColoring) {
                // 涂色模式：找到点击的单元格
                const col = Math.floor(canvasX / cellWidth);
                const row = Math.floor(canvasY / cellHeight);
                const index = row * cols + col;
                
                if (index >= 0 && index < cells.length) {
                    // 切换涂色状态并启动动画
                    cells[index].isColored = !cells[index].isColored;
                    
                    if (!isAnimating) {
                        isAnimating = true;
                        updateAnimation();
                    }
                }
            }
        });
        
        canvas.addEventListener('touchmove', (e) => {
            e.preventDefault();
            if (!isMouseDown) return;
            
            const rect = canvas.getBoundingClientRect();
            const x = e.touches[0].clientX;
            const y = e.touches[0].clientY;
            
            if (isDrawing) {
                // 计算触摸点在画布上的精确位置
                const scaleX = canvas.width / rect.width;
                const scaleY = canvas.height / rect.height;
                const canvasX = (x - rect.left) * scaleX;
                const canvasY = (y - rect.top) * scaleY;
                
                // 添加点到分割线
                splitLine.push({ x: canvasX, y: canvasY });
                drawCanvas();
            } else if (isColoring) {
                // 涂色模式：找到触摸移动经过的单元格
                const canvasX = x - rect.left;
                const canvasY = y - rect.top;
                
                const col = Math.floor(canvasX / cellWidth);
                const row = Math.floor(canvasY / cellHeight);
                const index = row * cols + col;
                
                if (index >= 0 && index < cells.length && !cells[index].isColored) {
                    // 设置单元格为涂色状态并启动动画
                    cells[index].isColored = true;
                    
                    if (!isAnimating) {
                        isAnimating = true;
                        updateAnimation();
                    }
                }
            }
        });
        
        canvas.addEventListener('touchend', (e) => {
            e.preventDefault();
            isMouseDown = false;
        });
        
        // 窗口大小变化时重新设置Canvas
        window.addEventListener('resize', setupCanvas);
        
        // 初始化
        initSlider();
        setupCanvas();
    </script>
</body>
</html>
